package com.butterfly.hotkey.client.core.collector;


import com.butterfly.hotkey.client.core.collector.segment.ISegment;

import java.util.Collection;
import java.util.Map;

/**
 * @author butterfly
 * @since 2024/11/1
 */
public abstract class AbstractSegmentCollector<K, V, SV> implements IKeyCollector<K, V> {

    /**
     * 双buffer
     */
    protected ISegment<K, SV>[] segments;

    /**
     * 当前使用的哪一个Segment
     */
    protected volatile int currentPos;

    public AbstractSegmentCollector() {
        this.currentPos = 0;
    }

    protected void switchPos() {
        currentPos = nextPos();
    }

    protected int nextPos() {
        return (currentPos + 1) % 2;
    }

    @Override
    public void collect(K key) {
        if (key == null) {
            return;
        }
        ISegment<K, SV> segment = segments[currentPos];
        segment.addKey(key);
    }

    @Override
    public Collection<V> getCollection() {
        // 每次推送切换分片，并清空数据
        ISegment<K, SV> segment = segments[currentPos];
        switchPos();
        Map<String, SV> segmentMap = segment.getSegment();
        Collection<V> collection = convertSegment(segmentMap);
        segment.clear();
        return collection;
    }

    /**
     * 转换分片数据
     *
     * @param segmentMap segmentMap
     * @return 数据
     */
    protected abstract Collection<V> convertSegment(Map<String, SV> segmentMap);

}
